package com.wny.activities;


import java.io.IOException;
import java.net.UnknownHostException;

import com.wny.R;
import com.wny.backend.SocketsClient;
import android.app.Activity;
import android.content.Intent;
import android.location.LocationListener;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;

public class LoginActivity extends Activity{
	Button loginBtn;
	Button signupBtn;
	OnClickListener loginListener = null;
	OnClickListener signupListener = null;

	String save_username = null;
	String save_password = null;

	SocketsClient socket;
	String serverIP;
	
	String username;
	int uid = -1;

	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			serverIP = extras.getString("serverIP");
		}
		loginListener = new OnClickListener() {
			public void onClick(View v) {
				Intent logIntent = new Intent(LoginActivity.this,
						MainMenuActivity.class);
				setTitle("Main Menu");			
				if (tryLogin(v) == true) {	
					displayWithToast("Sucessfuly logged in", 4000);
					logIntent.putExtra("uid", uid);	
					startActivity(logIntent);
				} else {
					
					displayWithToast("Invalid login.", 4000);
				}

			}
		};
		signupListener = new OnClickListener() {
			public void onClick(View v) {
				Intent signIntent = new Intent(LoginActivity.this,
						SignUpActivity.class);
				setTitle("Sign Up");
				startActivity(signIntent);
			}
		};
		setContentView(R.layout.login);
		loginBtn = (Button) findViewById(R.id.login);
		loginBtn.setOnClickListener(loginListener);
		signupBtn = (Button) findViewById(R.id.signUp);
		signupBtn.setOnClickListener(signupListener);
	}

	public boolean tryLogin(View V)

	{
		boolean isValid = false;
		// The Username and password for user
		String username = ((EditText) findViewById(R.id.logUsername)).getText()
				.toString();
		String password = ((EditText) findViewById(R.id.logPassoword))
				.getText().toString();
	
		
		char[] t = { '0' };
		// initializes the SQL query to log in a user
		StringBuilder toSend = new StringBuilder("other=log&name=");
		// Sees if remember me box is selected, if it is, remember them and
		// autofill the username and password slots
		if ( ((CheckBox) findViewById(R.id.checkRememberMe)).isChecked()) {

			if ((save_username == null)|| (username != save_username && username.length() != 0)) {

				saveLoginInfo(username, password);
			}
			// autofills user credentials
			FillinCredientals(V);
			// send remember me credentials to server
			try {
				t = socket.sendData((toSend + save_username + "&pwd="
						+ save_password + "\n").getBytes());
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		else {
			// otherwise remember me is not checked. Just send the current
			// username and password to server
			try {
				t = socket
						.sendData((toSend + username + "&pwd=" + password + "\n")
								.getBytes());
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// if first bit is 1, query is successful. User is admitted into the
		// program
		if (t[0] == '1') {	
			setUID(username);
			isValid = true;
			if  ( !((CheckBox) findViewById(R.id.checkRememberMe)).isChecked()){
				EditText clear_username = ((EditText) findViewById(R.id.logUsername));
				EditText clear_password = ((EditText) findViewById(R.id.logPassoword));
				clear_username.setText("");
				clear_password.setText("");
			}

		} else {
			char testlogin []={'0'};
			try {
				testlogin=socket.sendData( ("get=user&name=" +username+"\n").getBytes());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String user[]=(String.valueOf(testlogin)).split("/");
	
			if(user[1].equals(username) && !(user[2].equals(password)) ){
				displayWithToast("Error-password is incorrect",4000);
			}
			isValid = false;
		}

		return isValid;

	}

	public void FillinCredientals(View V) {

		// checks to see parameters are not null. It then fills in the username
		// ans password
		if (save_username != null || save_password != null) {
			// fill in the username and password automatically when checked
			EditText username = ((EditText) findViewById(R.id.logUsername));
			username.setText(save_username);
			EditText password = ((EditText) findViewById(R.id.logPassoword));
			password.setText(save_password);
		}
	}

	// saves remember me credentials
	private void saveLoginInfo(String username, String password) {
		save_username = username;
		save_password = password;
	}

	// a wrapper function for the Toast class. Used to show messages onscreen
	private void displayWithToast(String toShow, int duration) {
		Toast temp = Toast.makeText(this, toShow, duration);
		temp.setGravity(Gravity.CENTER, 0, 0);
		temp.show();
	}
	
	private void setUID(String username){
		try{
		char[] uid = socket.sendData(("getid=user&name=" + username + "\n")
				.getBytes());
		this.uid = Integer.valueOf(String.valueOf(uid).split("/")[0]);
		}catch(IOException e){
			e.printStackTrace();
		}
		
	}

	// the Restart,onResume,Pause, and Stop functions deals with loopback with
	// Android emulator
	// loopback for Anroid emulator is 10.0.2.2 (not 127.0.0.1!)
	protected void onStart() {
		super.onStart();
		socket = SocketsClient.getSocket();
	}

	protected void onResume() {
		super.onResume();
		socket = SocketsClient.getSocket();
	}

	protected void onPause() {
		super.onPause();
	}

	protected void onStop() {
		super.onStop();
	}

}
